package com.student.xujiang.myallstudent.okhttp3;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.student.xujiang.R;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttp3MainActivity extends AppCompatActivity {

    String TAG = this.getClass().getSimpleName();

    //指定表单类型 下面为默认
    private static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");
    /**
     * 如果表单是个json：
     * MediaType JSON = MediaType.parse("application/json; charset=utf-8");
     * RequestBody body = RequestBody.create(JSON, "你的json");
     *
     * 如果数据包含文件：
     * RequestBody requestBody = new MultipartBody.Builder()
     * .setType(MultipartBody.FORM)
     * .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
     * .build();
     *
     * 上面的MultipartBody也是继承了RequestBody，看下源码可知它适用于这五种Content-Type:
     * public static final MediaType MIXED = MediaType.parse("multipart/mixed");
     * public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative");
     * public static final MediaType DIGEST = MediaType.parse("multipart/digest");
     * public static final MediaType PARALLEL = MediaType.parse("multipart/parallel");
     * public static final MediaType FORM = MediaType.parse("multipart/form-data");
     *
     *http://www.w3school.com.cn/media/media_mimeref.asp
     *
     * */

    @BindView(R.id.okhttp3_main_tv)
    TextView okhttp3MainTv;
    @BindView(R.id.activity_ok_http3_main)
    RelativeLayout activityOkHttp3Main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http3_main);
        ButterKnife.bind(this);

        String html = okhttpget();
        if(html != null){
            okhttp3MainTv.setText(html);
        }

        okhttppost();

        okhttpasynchronousget();


    }



    private void okhttppost() {
        String url = "https://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient();

        /**
         *         RequestBody的数据格式都要指定Content-Type，常见的有三种：
         *         application/x-www-form-urlencoded 数据是个普通表单
         *         multipart/form-data 数据里有文件
         *         application/json 数据是个json
         *
         */
        RequestBody body = new FormBody.Builder()
                .add("user", "15223782694")
                .add("page", "1000")
                .build();

        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        final Call call = okHttpClient.newCall(request);

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response response = call.execute();
                        Log.i(TAG,response.body().string());
                        //此处需要消息传递。。。
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();


    }

    //okhttp的get方法
    private String okhttpget() {
        String url = "https://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient();

        final Request request = new Request.Builder()
                .url(url)
                //.header("键", "值")  //添加头
                //.header("键", "值")
                .build();

        final Call call = okHttpClient.newCall(request);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = call.execute();
                    Log.i(TAG,response.body().string());
                    //此处需要消息传递。。。
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        return null;
    }

    /**
     * 以上为同步写法  不建议这么写
     *
     * 下面为异步
     * */

    private void okhttpasynchronousget() {
        String url = "https://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("我是异步线程,线程Id为:" + Thread.currentThread().getId());
                okhttp3MainTv.setText(response.body().string());
            }
        });

        for (int i = 0; i < 10; i++) {
            System.out.println("我是主线程,线程Id为:" + Thread.currentThread().getId());
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     *
     * Request经常都要携带Cookie，上面说过request创建时可以通过header设置参数，Cookie也是参数之一。就像下面这样：
     *
     * Request request = new Request.Builder()
     .url(url)
     .header("Cookie", "xxx")
     .build();
     *
     *
     * 然后可以从返回的response里得到新的Cookie，你可能得想办法把Cookie保存起来。
     但是OkHttp可以不用我们管理Cookie，自动携带，保存和更新Cookie。
     方法是在创建OkHttpClient设置管理Cookie的CookieJar：
     *
     *
     *
     *private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
     OkHttpClient okHttpClient = new OkHttpClient.Builder()
     .cookieJar(new CookieJar() {
    @Override
    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
    cookieStore.put(httpUrl.host(), list);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl httpUrl) {
    List<Cookie> cookies = cookieStore.get(httpUrl.host());
    return cookies != null ? cookies : new ArrayList<Cookie>();
    }
    })
     .build();
     *
     *
     * */





}
